<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function farmer_list_page()
{
    global $user;
    $user_info = _get_user_info($user->uid);
    if ($user_info['role'] === '农户') {
        drupal_goto('farmer/edit/' . $user->uid);
    }
    @$output = drupal_render(drupal_get_form('farmer_list_form'));
    return $output;
}

function farmer_list_form($form, &$form_state)
{
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    $form['status'] =  _insert_user_upgrade_status_selection_form($form, $form_state,$role="farmer",$init_value = "");
    if (empty($form_state['addr_id'])) {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,'');
        $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '', TRUE);
    }else{
        $form['#addr_id'] = $form_state['addr_id'];
        $addr_red = get_all_addrname($form['#addr_id']);
        $province = $addr_red[0]->province?$addr_red[0]->province:"";
        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
        $form['#addr'] =$province.$city.$county.$town.$village;
    }
    $form['distributor_name'] = _insert_distributor1_selection_form($form, $form_state, 'address_distributor');
    $form['farmername'] = array(
        '#attributes' => array('placeholder' => '农户姓名'),
        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['retailname']) ? $form_state['values']['farmername'] : '',
    );
    $form['telephone'] = array(
        '#attributes' => array('placeholder' => '手机'),
        '#type' => 'textfield',
        '#maxlength' => 11,
        '#default_value' => !empty($form_state['values']['telephone']) ? $form_state['values']['telephone'] : '',
    );
    if(!empty($_GET['special_activities'])){
        $special_activities_title = get_special_activities_title($_GET['special_activities']);
    }
    $form['special_activities'] = array(
        '#type' => 'textfield',
        '#title' => '专项活动',
        '#size' => 32,
        '#maxlength' => 50,
        '#id'=>'special_activities_textfield',
        '#default_value' => $special_activities_title,
    );
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function farmer_list_form_validate($form, &$form_state)
{
}

function data_list_view_page(&$form = '', &$form_state = '')
{
    global $user;
    $output = '';
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
        array('data' => '地址', 'class' => ['essential province city county']),
        array('data' => '农户姓名', 'class' => ['essential farmer_name']),
        array('data' => '手机', 'class' => ['essential break cell']),
        array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '土壤种类', 'class' => ['essential soil_type']),
        array('data' => '土壤肥沃度', 'class' => ['essential soil_fertility']),
        array('data' => '耕地面积', 'class' => ['integrant essential break farm_area'], 'field' => 'farm_area'),
        array('data' => '状态', 'class' => ['integrant essential break status'], 'field' => 'status'),
        array('data' => '操作', 'class' => ['essential more']),
    );

    $query = db_select('farmer', 'F')->extend('PagerDefault')->extend('TableSort');//->extend('Statistics');
//    $query->join('farmer', 'F', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=F.addr_id');

    $query->leftJoin('distributor', 'D', 'D.distributor_id=F.distributor_id');
    //地址级别查询
    _address_search_conditon($query,$form_state);
    //模糊条件筛选
    if (!empty($form_state['values']['farmername'])) {//农户名字
        $query->condition('F.farmer_name', '%' . db_like($form_state['values']['farmername']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['telephone'])) {//模糊电话号码查询条件
        $query->condition('F.cell', '%' . db_like($form_state['values']['telephone']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['status'])) {//模糊植物名字查询条件
        $query->condition('F.status',$form_state['values']['status']);
    }
    if (isset($form_state['addr_id']) && !empty($form_state['addr_id'])) {
        $query->condition('F.addr_id', $form_state['addr_id']);
    }
    if (!empty($form_state['values']['distributor'])) {//查询条件
//        $query->condition('V.distributor_id', $form_state['values']['distributor'], '=');
        $query->condition('D.distributor_name', '%'.db_like($form_state['values']['distributor']).'%', 'LIKE');
    }
    if(!user_access('view all farmer') && user_access('view own farmer')){
        $query->condition('F.author_uid',$user->uid, '=');
    }
    //专项活动
    if(!empty($form_state['values']['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('F.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('F.special_activities_id',0, '=');
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('F.special_activities_id',$_GET['special_activities'], '=');
    }
    $query->fields('F');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('D', 'distributor_name');
    $query->addField('D', 'distributor_id');
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('F.timestamp', 'DESC');
    }
    //统计
    $statQuery = $query->cloneQuery();
    $statQuery->addExpression('format(avg(F.farm_area),2)','avg_farm_area');
    $statQuery->addExpression('count(*)','count');
    $statInfo = $statQuery->execute()->fetchObject();
    $form["#stat"]['#count'] = $statInfo->count;
    $form["#stat"]['#avg_farm_area'] = $statInfo->avg_farm_area;

    $query->limit(variable_get("list_page_item_number", 5));
    $farmerInfo = $query->orderByHeader($header)->execute()->fetchAll();

    $rows = array();
    //表内容
    $n = 1;
    foreach ($farmerInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        $town = $row->town ? ' ' . $row->town : '';
        $village = $row->village ? ' ' . $row->village : '';

        if (nonghua_user_access('farmer', 'delete', $row->farmer_id, $row->author_uid, $row->farmer_id)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }

        $rows[] = array(

            array('data' => "<input type='checkbox'".$disabled." value ='" . $row->farmer_id . "' name='" . $row->farmer_id . "'/>" . $n++, 'class' => 'integrant essential no'),
            isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
            array('data' =>'<a href="'.base_path().'village/edit/' . $row->addr_id . '?addr_id='.$row->addr_id.'">'. $row->province . $city . $county . $town . $village."</a>", 'class' => ['integrant haveTobr essential province city county']),
            array('data' => '<a href="' . base_path() . 'farmer/overview?farmer_id='.$row->farmer_id.'">' . $row->farmer_name . "</a>", 'class' => ['integrant goRight essential farmer_name']),
            array('data' => $row->cell, 'class' => ['essential break cell']),
            array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '" data-toggle="modal" target = "_blank">' . $row->distributor_name . '</a>', 'class' => ['essential distributor_name']),
            array('data' => $row->soil_type, 'class' => ['essential soil_type']),
            array('data' => $row->soil_fertility, 'class' => ['essential soil_fertility']),
            array('data' => $row->farm_area, 'class' => ['integrant haveTobr essential break farm_area']),
            array('data' => $row->status, 'class' => ['integrant haveTobr essential break status']),
            isset( $form_state['addr_id']) && !empty( $form_state['addr_id'])?
            array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?addr_id='.$form_state['addr_id'].'"
            data-toggle="modal" target="_self"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>',
                'class' => 'essential more'):
            array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '"
            data-toggle="modal" target="_self"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>',
                'class' => 'essential more'),
        );
    }


    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own farmer') ||  user_access('delete all farmer'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'farmer/export?'.$str.'&status='.$form_state['values']['status'].'&farmername='.$form_state['values']['farmername'].'&telephone='.$form_state['values']['telephone'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
//    dpm($output);die;
    $output .= theme('pager');
    return $output;
}

function farmer_delete()
{
    ajax_table_delete('farmer', 'farmer_id', true);
}

function farmer_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','经销商','详细地址','农户','农户电话','邮箱','性别','土壤种类','土壤肥沃度', '耕地面积');
    $data = get_farmer_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'农户信息数据');
}

function get_farmer_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('addr', 'A');
    $query->join('farmer', 'F', 'A.addr_id=F.addr_id');

    $query->leftJoin('distributor', 'D', 'D.distributor_id=F.distributor_id');
    //地址级别查询
    $addr_sql = '';
    if (!empty($_GET['village'])) {//乡镇级
        $query->condition('A.village_id', $_GET['village'], '=');
    } elseif (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id',$_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    //模糊条件筛选
    if (!empty($_GET['farmername'])) {//农户名字
        $query->condition('F.farmer_name', '%' . db_like($_GET['farmername']) . '%', 'LIKE');
    }
    if (!empty($_GET['telephone'])) {//模糊电话号码查询条件
        $query->condition('F.phone', '%' . db_like($_GET['telephone']) . '%', 'LIKE');
    }
    if (!empty($_GET['status'])) {//模糊植物名字查询条件
        $query->condition('F.status',$_GET['status']);
    }
    if (isset($_GET['addr_id']) && !empty($_GET['addr_id'])) {
        $query->condition('F.addr_id', $_GET['addr_id']);
    }
    if(!user_access('view all farmer') && user_access('view own farmer')){
        $query->condition('F.author_uid',$user->uid, '=');
    }
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('D', 'distributor_name');
    $query->fields('F',array('addr_details','farmer_name','phone','email','gender','soil_type','soil_fertility','farm_area'));
    if(empty($form_state['values'])) {
        $query->orderBy('F.timestamp', 'DESC');
    }
    $farmerInfo = $query->execute()->fetchAll();
    foreach($farmerInfo as $k => $v){
        $farmerInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($farmerInfo[$k]->city);
        unset($farmerInfo[$k]->county);
        unset($farmerInfo[$k]->town);
        unset($farmerInfo[$k]->village);
    }
    return $farmerInfo;
}